package com.ruoyi.web.controller.webContent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.utils.DictUtils;
import com.ruoyi.web.controller.tool.ApplicationContextUtil;
import com.ruoyi.web.controller.tool.EmailUtils;
import com.ruoyi.webContent.domain.Mt5Point;
import com.ruoyi.webContent.domain.PlCalculateResult;
import com.ruoyi.webContent.domain.PlEmailSended;
import com.ruoyi.webContent.domain.PlHostTrade;
import com.ruoyi.webContent.mapper.PlCalculateResultMapper;
import com.ruoyi.webContent.mapper.PlEmailSendedMapper;
import com.ruoyi.webContent.service.IMt5PointService;
import com.ruoyi.webContent.service.IPlCalculateResultService;
import com.ruoyi.webContent.service.IPlHostTradeService;
import com.ruoyi.webContent.service.IPlTeamService;
import org.apache.commons.collections.ListUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * mt5PointController
 *
 * @author ruoyi
 * @date 2020-06-29
 */
@Controller
@RequestMapping("/pl/rest")
public class PlRestController extends BaseController {


//    @Autowired
//    private IPlCalculateResultService plCalculateResultService;

//    private Map<String,List<PlCalculateResult>> roleResult = new HashMap<>();


    /**
     * 新增mt5Point
     */
    @GetMapping("/sendEmail")
    @ResponseBody
    public void sendEmail(Long roleId) {
        IPlCalculateResultService plCalculateResultService = (IPlCalculateResultService) ApplicationContextUtil.getBean("plCalculateResultServiceImpl");
        PlCalculateResult searchRes = new PlCalculateResult();
        searchRes.setRes(0L);
        List<PlCalculateResult> list = new ArrayList<>();
        String head = "Oh!";
        if(roleId.toString().equals("2")){
            list = plCalculateResultService.selectPlCalculateResultList(searchRes);
            head+="common>>>";

        }
        if(roleId.toString().equals("3")){
            list = plCalculateResultService.selectPlCalculateResultListVip(searchRes);
            head+="vip>>>";

        }
        if(list.size()==0){
            return;
        }
        IPlHostTradeService plHostTradeService = (IPlHostTradeService) ApplicationContextUtil.getBean("plHostTradeServiceImpl");
        String str = "";
        List<PlCalculateResult> sendedRes = new ArrayList<>();
        for (PlCalculateResult res:list) {
            String id = res.getGameName()+"_"+res.getHostACode()+"_"+res.getHostBCode()+"_"+res.getPlType()+"_"+res.getHostAView()+"_"+res.getRes();
            PlEmailSended plEmailSended = plCalculateResultService.selectPlEmailSendedById(id);
            if(plEmailSended!=null){//
                continue;
            }
            addTrade(plHostTradeService, res);
            sendedRes.add(res);
            PlEmailSended emailSended = new PlEmailSended();
            emailSended.setId(id);
            plCalculateResultService.insertPlEmailSended(emailSended);
            str += head+res.getStartDate()+";"+res.getPlType()+";"+res.getHostA()+":"+res.getHostB()+";"+res.getGameName()+"(1.LOL，2.CS，3.Dota);"
                    +res.getHostAView()+";"+res.getHostAPl()+";"+res.getHostBPl()+":LR："+res.getRes()+"\r\n";
        }
        SysUser searchUser = new SysUser();
        searchUser.setRoleId(roleId);
        SysUserMapper userMapper = (SysUserMapper) ApplicationContextUtil.getBean("sysUserMapper");
        List<SysUser> sysUsers = userMapper.selectAllocatedList(searchUser);

        if(str.length()<10){
            return;
        }
        for (SysUser user:sysUsers) {
            try {
                //发送
                EmailUtils.sendEmail(user.getEmail(), head+str,str);
                //得出 common:results
//                roleResult.put(head.replace(">>>",""),sendedRes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public void addTrade(IPlHostTradeService plHostTradeService, PlCalculateResult res) {
        //因为可能存在同一个marketId对应了不同网站的marketId,那么数据会出现异常
        String trateId = res.getHostAmarketId() + "_" + res.getHostBmarketId();
        PlHostTrade plHostTrade = plHostTradeService.selectPlHostTradeById(res.getHostAmarketId() + "_" + res.getHostAmarketId());
        if(plHostTrade==null){
            //插入网站A
            PlHostTrade tradeA = new PlHostTrade();
            BeanUtils.copyProperties(res,tradeA);
            tradeA.setHostAMarketIdHostBMarketId(trateId);
            tradeA.setTradeStatus("0");
            tradeA.setHostCompare(res.getHostB());
            plHostTradeService.insertPlHostTrade(tradeA);
            //插入网站A
            PlHostTrade tradeB = new PlHostTrade();
            BeanUtils.copyProperties(res,tradeB);
            tradeB.setHostAMarketIdHostBMarketId(res.getHostBmarketId() + "_" + res.getHostAmarketId());
            tradeB.setHostA(res.getHostB());
            tradeB.setHostAmarketId(res.getHostBmarketId());
            tradeB.setHostBmarketId(res.getHostAmarketId());
            tradeB.setHostACode(res.getHostBCode());
            tradeB.setHostAView(res.getHostBView());
            tradeB.setHostCompare(res.getHostA());
            tradeB.setHostAPl(res.getHostBPl());
            tradeB.setTradeStatus("0");
            plHostTradeService.insertPlHostTrade(tradeB);
        }
    }

    /**
     * 检查各个网站连接状态
     * @throws Exception
     */
    public void checkHostStatus() throws Exception{
        IPlCalculateResultService plCalculateResultService = (IPlCalculateResultService) ApplicationContextUtil.getBean("plCalculateResultServiceImpl");
        List<SysDictData> pl_rest_url = DictUtils.getDictCache("pl_rest_url");
        for (SysDictData hostRest:pl_rest_url) {
            int  timeOut =  3000 ;  //超时应该在3钞以上
            //启用状态
            if(hostRest.getStatus().equals("0")){
                String hostAdress = hostRest.getDictValue();
                String adress = hostAdress.substring(hostAdress.indexOf("//") + 2);
                boolean status = InetAddress.getByName(adress).isReachable(timeOut);     // 当返回值是true时，说明host是可用的，false则不可。
                if(status==false){
                    List<SysUser> sysUsers = plCalculateResultService.selectUserList(new SysUser());
                    for (SysUser user:sysUsers) {
                        try {
                            EmailUtils.sendEmail("570289129@qq.com", "接口连接异常告警！！！"+hostRest.getDictLabel(),hostRest.getDictLabel()+"接口连接异常告警！！！");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }


}
